import { App, Dropdown, Flex } from 'antd';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

import orchestrationService from '@/api/services/orchestrationService';
import bgLayer from '@/assets/images/background/bg-layer.png';
import bgPrcture from '@/assets/images/background/bg-prcture.png';
import { GetWorkBenhList } from '@/common';
import {
  AppCreateTypeEnum,
  AppStatusEnum,
  AppType,
  AppWorkbenchType,
} from '@/common/app/constants';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useTiangongRole } from '@/hooks/useTiangongRole';
import SharelinkModal from '@/pages/share-link-manage/components/SharelinkModal';
import { useDatasetStore } from '@/store/datasetStore';
import { useUserInfo } from '@/store/userStore';
import { formatDataNoTime } from '@/utils/time';

import { SvgIcon } from '../icon';

import AppInfoModal from './components/AppInfoModal';
import AvatarDisplay from './components/AvatarDisplay';
import NewAgentModeModal from './components/NewAgentModeModal';
import WorkDropdown from './work-dropdown';
import './work.scss';

interface WorkBoxProps {
  type: string; // manager,public, market
  dataList: Array<GetWorkBenhList>;
  isGetFusion?: boolean;
  changeCollect?: (data: GetWorkBenhList) => void;
  onGetFusionCollect?: (data: GetWorkBenhList) => void;
}

export default function WorkBox({
  type,

  dataList,
  isGetFusion,
  changeCollect = () => {},
  onGetFusionCollect = () => {},
}: WorkBoxProps) {
  const [isShow, setIsShow] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('');
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const [searchIndex, setSearchIndex] = useState<number>(0);
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [onOpen, setOnOpen] = useState<boolean>(false);
  const [blangTitle, setBlangTitle] = useState<string>('');
  const [openedDropdownId, setOpenedDropdownId] = useState<number | null>(null);
  const router = useNavigate();
  const [workItems, setWorkItems] = useState<GetWorkBenhList>();
  const [searchText, setSearchText] = useState<string>('');
  const { isPc } = useWindowWidth();
  const { role, username } = useUserInfo();
  const [template, setTemplate] = useState<any>({});
  const [allDataList, setAllDataList] = useState<Array<GetWorkBenhList>>([]);

  const [newAgentOpen, setNewAgentOpen] = useState<boolean>(false);

  // 应用分享
  const [shareModalOpen, setShareModalOpen] = useState<boolean>(false);
  const [currentAppId, setCurrentAppId] = useState<string>('');
  const { loadAllDatasets } = useDatasetStore();
  const { t } = useTranslation();
  const { message } = App.useApp();
  const { isTiangongManager } = useTiangongRole();
  useEffect(() => {
    setAllDataList(dataList);
  }, [type, dataList]);

  const baseStyle: React.CSSProperties = {
    width: isPc ? '' : '100%',
    height: 238,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 12,
    border: '1px solid #FFFFFF',
    cursor: 'pointer',
    flexShrink: 0,
    fontWeight: 500,
    // background: '#EEF0F4',
    background: '#FFFFFF',
    opacity: 0.85,
  };

  const baseStyle1: React.CSSProperties = {
    width: isPc ? '' : '100%',
    height: 238,
    borderRadius: 12,
    // padding: '12px 20px ',
    // background: `url(${type === 'market' ? bgPrcture : bgLayer}) no-repeat #F8FAFB center top`,
    background: `${type === 'market' ? '#FFFFFF' : '#FFFFFF'}`,
    // backgroundSize: type === 'market' ? '100% 50%' : '50% 50%',
    // border: '1px solid #F8FAFB',
    // border: '2px solid #FFFFFF',
    cursor: 'pointer',
    position: 'relative',
    flexShrink: 0,
    opacity: 0.85,
    border: ' 2px solid transparent',
    boxShadow: ' inset 0 0 0 1px var(--line-0) ',
  };

  const onShareAgent = (e: any, item: any) => {
    const reviewStatus = item.review_status;
    if (reviewStatus != AppStatusEnum.pass) {
      if (reviewStatus === AppStatusEnum.pending) {
        message.info(t('page.shareLink.review_pending'));
      } else if (reviewStatus === AppStatusEnum.reject) {
        message.info(t('page.shareLink.review_reject'));
      } else {
        message.info(t('page.shareLink.review_unpublished'));
      }
      return;
    }
    e.stopPropagation();
    loadAllDatasets({
      parentId: '',
      app_id: item.app_id,
      isPage: false,
    });
    setShareModalOpen(true);
    setCurrentAppId(item.app_id);
    onUpdateWork();
  };

  const generateMenuItems = (
    item: any,
    onUpdateWork: any,
    t: any,
    loadAllDatasets: any,
    setShareModalOpen: any,
    setCurrentAppId: any,
  ) => {
    const baseItems = [
      {
        key: '1',
        label: <WorkDropdown items={item} icon="message-ic16" title="编辑" />,
      },
    ];

    // 如果是管理员，添加额外菜单项
    if (item.roles_for_user_in_app?.includes('admin')) {
      return [
        // ...(item.app_type === AppType.fusion
        //   ? []
        //   : [
        //       {
        //         key: '0',
        //         label: (
        //           <div
        //             onClick={(e) => {
        //               const reviewStatus = item.review_status;
        //               if (reviewStatus != AppStatusEnum.pass) {
        //                 if (reviewStatus === AppStatusEnum.pending) {
        //                   message.info(t('page.shareLink.review_pending'));
        //                 } else if (reviewStatus === AppStatusEnum.reject) {
        //                   message.info(t('page.shareLink.review_reject'));
        //                 } else {
        //                   message.info(t('page.shareLink.review_unpublished'));
        //                 }
        //                 return;
        //               }
        //               e.stopPropagation();
        //               loadAllDatasets({
        //                 parentId: '',
        //                 app_id: item.app_id,
        //                 isPage: false,
        //               });
        //               setShareModalOpen(true);
        //               setCurrentAppId(item.app_id);
        //               onUpdateWork();
        //             }}
        //             className="h-[25px] w-[80px] pl-[28px] text-[12px] leading-[25px] text-[#1D2129]"
        //           >
        //             分享
        //           </div>
        //         ),
        //       },
        //     ]),

        // ...baseItems,

        // 待审批中的应用，不支持审核员编辑
        ...(item.review_status === AppStatusEnum.pending && role?.code === 'super_admin'
          ? []
          : baseItems),

        {
          key: '2',
          label: (
            <WorkDropdown
              items={item}
              icon="message-ic15"
              title="复制"
              onUpdateWork={onUpdateWork}
            />
          ),
        },
        {
          key: '3',
          label: (
            <WorkDropdown
              items={item}
              icon="message-ic3"
              title="删除"
              onUpdateWork={onUpdateWork}
            />
          ),
        },
      ];
    }

    return baseItems;
  };

  function onUpdateWork() {
    setOpenedDropdownId(null);
    setSearchText('');
  }

  function mouseEvent(e: number) {
    return () => {
      setActiveIndex(e);
    };
  }

  function mouseLeave() {
    return () => {
      setOpenedDropdownId(null);
      setActiveIndex(-1);
    };
  }
  async function goToApplication(e: React.MouseEvent, obj: GetWorkBenhList) {
    if (isGetFusion) {
      onGetFusionCollect(obj);
      return;
    }

    // 公共函数：打开聊天应用
    const openChatApp = (appId: string, shareId: string, type: string) => {
      if (isPc) {
        try {
          const newWindow = window.open(
            type == 'fusion'
              ? `/fusion?appId=${appId}&shareId=${shareId}`
              : `/apps/chat?appId=${appId}&shareId=${shareId}`,
          );
          newWindow && (newWindow.opener = null);
        } catch {
          const link = document.createElement('a');
          link.href =
            type == 'fusion'
              ? `/fusion?appId=${appId}&shareId=${shareId}`
              : `/apps/chat?appId=${appId}&shareId=${shareId}`;
          link.target = '_blank';
          link.rel = 'noopener noreferrer';
          link.click();
        }
      } else {
        // router(`/apps/chat?appId=${appId}&shareId=${shareId}`);
        router(
          type == 'fusion'
            ? `/fusion?appId=${appId}&shareId=${shareId}&isPublic=true`
            : `/apps/chat?appId=${appId}&shareId=${shareId}&isPublic=true`,
        );
      }

      // router(type == 'fusion' ? `/fusion?appId=${appId}&shareId=${shareId}` : `/apps/chat?appId=${appId}&shareId=${shareId}`);
    };

    if (type === 'manager') {
      // 待审批中的应用，审核员跳转审核页面
      if (obj.review_status === AppStatusEnum.pending && role?.code === 'super_admin') {
        if (obj.app_type === 'agent') {
          router(`/apps/viewOrchestration?appType=${obj.app_type}&appId=${obj.app_id}`);
        } else {
          router(
            `/apps/viewOrchestration?appType=${obj.app_type}&appId=${obj.app_id}&currentTab=preview`,
          );
        }
        return;
      }
      // 统一处理管理员路由
      const getShareId = async () => {
        return (
          obj.share_id ||
          (await orchestrationService.getAppDetailV2(obj.app_id, AppWorkbenchType.manage)).share_id
        );
      };

      const shareId = await getShareId();
      obj.app_type === 'workflow'
        ? router(`/app/workflow?appId=${obj.app_id}&shareId=${shareId}`)
        : router(`/apps/orchestration?appId=${obj.app_id}&shareId=${shareId}`);
      return;
    }

    if (type === 'market') {
      goToAssistant(e, obj);
      return;
    }

    if (type === 'public' || type === 'fusion') {
      // 优先使用现有 share_id
      if (obj.share_id) {
        openChatApp(obj.app_id, obj.share_id, obj.app_type);
        return;
      }

      // 不存在时才请求
      const res = await orchestrationService.getAppDetailV2(obj.app_id, AppWorkbenchType.public);
      console.log('res', res);

      if (res.app_id && res.share_id) {
        openChatApp(res.app_id, res.share_id, obj.app_type);
      }
    }
  }
  function createApplication() {
    setNewAgentOpen(true);
    // setIsModalOpen(true);
    // 这个地方重新传数据
    // setModelData([...marketDataList, ...publicDataList])
  }

  // const handleOk = () => {
  //   setIsModalOpen(false);
  // };

  const handleCancel = () => {
    setIsModalOpen(false);
    setIsShow(false);
  };

  const changeToPage = async (num: number) => {
    setSearchIndex(num);
    setTemplate({});
    switch (num) {
      case 0:
        break;
      case 1:
        // 这里去空白页面
        handleCancel();
        setOnOpen(true); // 打开浮层
        setBlangTitle(AppCreateTypeEnum.agent);
        break;
      case 2:
        // 这里去工作流页面
        handleCancel();
        setOnOpen(true); // 打开浮层
        setBlangTitle(AppCreateTypeEnum.workflow);
        break;
      default:
        // 这里去融合页面
        handleCancel();
        setOnOpen(true); // 打开浮层
        setBlangTitle(AppCreateTypeEnum.fusion);
        break;
    }
  };
  const checkAllApplication = (type: string) => {
    setIsShow(true);
    if (type === 'manager') {
      setTitle('可管理应用');
    } else if (type === 'public') {
      setTitle('应用广场');
    } else {
      setTitle('应用模板');
    }
  };

  const goToAssistant = async (e: React.MouseEvent, obj: { app_id: string; app_type: string }) => {
    e.stopPropagation();
    setTemplate(obj);
    handleCancel();
    setOnOpen(true);
    if (obj.app_type == 'agent') {
      setBlangTitle(AppCreateTypeEnum.agent);
    }
    if (obj.app_type == 'workflow') {
      setBlangTitle(AppCreateTypeEnum.workflow);
    }
    if (obj.app_type == 'fusion') {
      setBlangTitle(AppCreateTypeEnum.fusion);
    }
  };

  return (
    <div>
      <Flex
        className="grid-row"
        style={
          isPc
            ? { minWidth: 290 }
            : { padding: '0 0px', display: 'flex', justifyContent: 'center', gap: 10 }
        }
      >
        {!isTiangongManager &&
          type === 'manager' &&
          isPc &&
          (role?.code === 'super_admin' || role?.code === 'admin') && (
            <div
              style={{ ...baseStyle }}
              onClick={() => createApplication()}
              className="jr-step-v2-2 jr2-step-v2-1 create-agent"
            >
              <SvgIcon icon="work-add" size={30} />
              <div className="mt-2  text-sm text-text-5 ">创建应用</div>
            </div>
          )}

        {Array.from(allDataList).map((item: any, i) => {
          // 生成当前项的菜单项
          const menuItems = generateMenuItems(
            item,
            onUpdateWork,
            t,
            loadAllDatasets,
            setShareModalOpen,
            setCurrentAppId,
          );

          return (
            <div
              key={i}
              style={
                // activeIndex === i ? { ...baseStyle1, border: '1px solid #4E87FF' } : { ...baseStyle1 }
                { ...baseStyle1 }
              }
              onMouseEnter={mouseEvent(i)}
              onMouseLeave={mouseLeave()}
              className="boxs box-hover w-min-[306px] relative flex flex-col items-center"
            >
              {type === 'market' ? (
                <img
                  src={item.scene_image.includes('.png') ? item.scene_image : bgPrcture}
                  alt=""
                  className="   h-[86px]  w-full justify-center rounded-tl-xl rounded-tr-xl "
                />
              ) : (
                <div
                  onClick={(e) => goToApplication(e, item)}
                  style={{
                    background: `url(${
                      type === 'market' ? bgPrcture : bgLayer
                    }) no-repeat #FFF  center top`,
                    backgroundSize: type === 'market' ? '100% 50%' : '50% 100%',
                    flexShrink: 0,
                    // border: '1px solid red',
                  }}
                  className="flex h-[106px] w-[287px] justify-center rounded-xl pt-[14px]"
                >
                  <div className=" ">
                    {type !== 'market' && (
                      <AvatarDisplay src={item.app_logo} size={50} className="h-[56px] w-[56px]" />
                    )}
                  </div>
                </div>
              )}
              <div
                className={`absolute top-[66px] z-10  px-4 pt-5 ${
                  type === 'market' ? ' backdrop-blur-md' : ' backdrop-blur-sm'
                }`}
                style={
                  type === 'market'
                    ? {
                        backgroundImage: `
            linear-gradient(to bottom, rgba(255,255,255,0.8) 0px, transparent 1px),
            linear-gradient(180deg, rgba(255, 255, 255, 0.3) 0%, #FFFFFF 100%)
          `,
                        backgroundSize: '100% 1px, 100% 100%',
                        backgroundRepeat: 'no-repeat',
                        width: '100%',
                      }
                    : {
                        borderTop: '1px solid transparent',
                        backgroundImage:
                          'linear-gradient(270deg, rgba(255, 255, 255, 0.04) 0%, #FFFFFF 50%, rgba(255, 255, 255, 0.04) 100%), linear-gradient(270deg, rgba(0, 0, 0, 0.04) 0%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.04) 100%)',
                        backgroundOrigin: 'border-box',
                        backgroundClip: 'border-box',
                        backgroundSize: '100% 1px, 100% 1px',
                        backgroundPosition: 'top left',
                        backgroundRepeat: 'no-repeat',
                        // border: '1px solid green',
                        width: '99%',
                      }
                }
                onClick={(e) => goToApplication(e, item)}
              >
                <div className="h-6 w-[95%] min-w-[50px] truncate text-base font-bold">
                  {item.app_name}
                </div>
                <div className=" mb-3 mt-1 flex items-center justify-between text-xs text-[#074B79]">
                  <div
                    className=" h-[18px] rounded-small px-[6px] text-xs leading-[18px]"
                    style={
                      item.app_type == 'agent'
                        ? { background: '#C0F8EF', color: '#00454D' }
                        : item.app_type == 'workflow'
                        ? { background: '#E3C7FD', color: '#280976' }
                        : { background: '#BADEFF', color: '#002379' }
                    }
                  >
                    {item.app_type == 'agent'
                      ? '智能体'
                      : item.app_type == 'workflow'
                      ? '工作流'
                      : '融合应用'}
                  </div>
                  <div className="flex h-5 w-2/4 justify-end text-xs">
                    <span className="mt-[1px] whitespace-nowrap text-[#C9CDD4]">By</span>
                    <div className="ml-2 flex max-w-[12em] items-center text-text-3">
                      <div className="max-w-[6em] truncate">{item.group_name}</div>
                      {!isTiangongManager && (
                        <>
                          <div className=" whitespace-nowrap">/</div>
                          <div className="max-w-[6em] truncate"> {item.user_name}</div>
                        </>
                      )}
                    </div>
                  </div>
                </div>
                <div className=" line-clamp-2 h-10 overflow-hidden  text-ellipsis  text-sm text-[#4E5969]">
                  <div className="text text-xs">
                    {item.review_status === 'reject' && '驳回原因:'}
                  </div>
                  {item.review_status === 'reject' ? item.review_description : item.app_description}
                </div>
              </div>
              <div
                className={`${
                  type === 'market' ? 'z-0 rounded-bl-xl rounded-br-xl bg-white' : 'z-10'
                } absolute bottom-0   w-full `}
              >
                <div className=" flex items-center justify-between rounded-md p-4 ">
                  <div className=" text-xs text-text-3">
                    {formatDataNoTime(item.create_time)}
                    <span className="ml-1">更新</span>
                  </div>
                  <div className="flex h-5 items-center">
                    {type === 'fusion' && (
                      <div
                        className="flex items-center"
                        onClick={() => {
                          changeCollect(item);
                        }}
                      >
                        {item.isCollect ? (
                          <SvgIcon icon="fusion-sc1" size={20} />
                        ) : (
                          <SvgIcon icon="fusion-sc" size={20} />
                        )}
                      </div>
                    )}
                    {type === 'manager' &&
                      item.app_type !== AppType.fusion &&
                      item.review_status === 'pass' && (
                        <div
                          className="mr-2 flex h-6  w-6 items-center justify-center text-text-3 hover:rounded-md hover:bg-fill-2 hover:!text-text-5 "
                          onClick={(e) => onShareAgent(e, item)}
                        >
                          <SvgIcon icon="message-ic18" size={20} />
                        </div>
                      )}
                    {type === 'manager' && (
                      <Dropdown
                        key={i}
                        open={openedDropdownId == i}
                        menu={{ items: menuItems }}
                        trigger={['click']}
                        arrow={false}
                        placement="bottomRight"
                        onOpenChange={(open) => {
                          setOpenedDropdownId(open ? i : null);
                        }}
                        overlayClassName="custom-dropdown"
                      >
                        <div
                          onClick={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                          }}
                          className="flex h-6 w-6 items-center justify-center text-text-3 hover:rounded-md hover:bg-fill-2 hover:!text-text-5 "
                        >
                          <SvgIcon icon="work-more" size={20} />
                          {/* <Space>
                            <EllipsisOutlined
                              style={{
                                fontSize: 25,
                                color: '#A5A9BB',
                              }}
                            />
                          </Space> */}
                        </div>
                      </Dropdown>
                    )}
                  </div>
                </div>
              </div>
              <div className="absolute right-0 top-0">
                {type === 'manager' && (
                  <div
                    className={`${
                      item.review_status === 'reject'
                        ? 'bg-functional-red text-error'
                        : item.review_status === 'pending'
                        ? 'bg-functional-orange text-warning'
                        : item.review_status === 'pass'
                        ? 'bg-functional-green text-primary'
                        : 'bg-functional-gray text-grays'
                    } ml-2 h-[22px] rounded-bl-2xl rounded-tr-[10px] px-3 pt-[2px]  text-center text-xs font-medium  text-[white]`}
                  >
                    {item.review_status === 'reject'
                      ? '驳回'
                      : item.review_status === 'pending'
                      ? '待审核'
                      : item.review_status === 'pass'
                      ? '发布'
                      : '未发布'}
                  </div>
                )}
              </div>

              {type === 'market' && (
                <div className="popup-content">
                  <div
                    className="popup-content-child"
                    onClick={(e) => {
                      goToAssistant(e, item);
                    }}
                  >
                    应用该模板
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </Flex>

      <NewAgentModeModal
        open={newAgentOpen}
        title="选中创建应用模式"
        goToAssistant={goToAssistant}
        goToApplication={goToApplication}
        setWorkItems={setWorkItems}
        changeToPage={changeToPage}
        onCancel={() => {
          setNewAgentOpen(false);
        }}
      />

      <AppInfoModal
        open={onOpen}
        appType={blangTitle}
        title={blangTitle === AppCreateTypeEnum.workflow ? '创建工作流' : '创建应用'}
        defaultAppName={template?.app_name}
        defaultAppDescription={template?.app_description}
        defaultAppLogo={template?.app_logo}
        defaultSceneImage={template?.scene_image} // 从模板中获取
        onOk={async (data) => {
          const res = await orchestrationService.createAppV2({
            app_type:
              blangTitle === AppCreateTypeEnum.workflow
                ? 'workflow'
                : blangTitle === AppCreateTypeEnum.agent
                ? 'agent'
                : 'fusion',
            app_name: data.appName,
            tag: data.tag,
            app_description: data.appDescription,
            app_logo: data.appLogo,
            scene_image: data.sceneImage,
            template_app_id: template?.app_id,
          });

          if (res.app_id) {
            orchestrationService.updateAppImage(res.app_id, {
              logo: data.appLogoList,
              scene: data.sceneImageList,
            });
            if (blangTitle === AppCreateTypeEnum.workflow) {
              router(`/app/workflow?appId=${res.app_id}&shareId=${res.share_id}`);
            } else if (blangTitle === AppCreateTypeEnum.agent) {
              router(`/apps/orchestration?appId=${res.app_id}&shareId=${res.share_id}`);
            } else {
              router(`/apps/orchestration?appId=${res.app_id}&shareId=${res.share_id}`);
            }
          } else {
            message.error('创建失败');
          }
        }}
        onCancel={() => {
          setOnOpen(false);
        }}
      />
      <SharelinkModal
        open={shareModalOpen}
        appIdValue={currentAppId}
        onCancel={() => {
          setShareModalOpen(false);
          setCurrentAppId('');
        }}
        title="创建分享链接"
      />
    </div>
  );
}
